<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <h2>助理设置</h2>
        <div class="action-buttons">
          <el-button type="primary" @click="showAddDialog">添加成员</el-button>
          <el-button @click="showBatchImportDialog">批量导入成员</el-button>
        </div>
      </div>
    </template>
    <!-- 查询表单区域 -->
    <div class="search-form">
      <el-select
          v-model="statusFilter"
          placeholder="请选择人员状态"
          class="search-select"
      >
        <el-option label="激活" value="激活"></el-option>
        <el-option label="冻结" value="冻结"></el-option>
      </el-select>
      <el-select
          v-model="roleFilter"
          placeholder="请选择系统角色"
          class="search-select"
      >
        <el-option label="系统管理员" value="系统管理员"></el-option>
        <el-option label="助理" value="助理"></el-option>
      </el-select>
      <el-input
          v-model="searchKey"
          placeholder="请输入姓名/账号/学号关键词查询"
          class="search-input"
      >
        <template #append>
          <el-button type="primary" @click="getList">查询</el-button>
        </template>
      </el-input>
      <el-button @click="resetFilters">重置</el-button>
    </div>
    <!-- 助理列表 -->
    <el-table
        :data="filteredData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="序号" width="60">
        <template #default="{ row }">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" width="80"></el-table-column>
      <el-table-column label="账号/学号" prop="account" width="100"></el-table-column>
      <el-table-column label="管辖范围" prop="jurisdiction" width="100"></el-table-column>
      <el-table-column label="联系电话" prop="phone"></el-table-column>
      <el-table-column label="系统角色" prop="role" width="140"></el-table-column>
      <el-table-column label="角色代码" prop="roleCode"></el-table-column>
      <el-table-column label="人员状态" prop="status">
        <template #default="{ row }">
          <el-tag :type="row.status === '激活' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" prop="addTime" width="170"></el-table-column>
      <el-table-column label="操作" width="80"> <!-- 调整列宽 -->
        <template #default="{ row }">
          <el-button size="small" @click="showChangeDialog(row)">变更</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部操作区 -->
    <div class="bottom-actions">
      <el-button type="primary" @click="batchChange">批量变更</el-button>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15]"
          layout="jumper, total, sizes, prev, pager, next"
          background
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!-- 变更弹窗 -->
    <el-dialog
        v-model="changeDialogVisible"
        :title="changeDialogTitle"
        width="500px"
    >
      <el-form
          ref="changeFormRef"
          :model="changeForm"
          :rules="changeRules"
          label-width="100px"
      >
        <div class="batch-change-dialog">
          <!-- 成员列表 -->
          <div
              v-for="(row, index) in batchRows"
              :key="index"
              class="member-item"
          >
            <span>{{ row.name }} - {{ row.account }}</span>
            <el-button
                type="text"
                @click="removeMember(index)"
                style="color: #f56c6c;"
            >
              移除
            </el-button>
          </div>
          <!-- 赋予角色 -->
          <div class="form-item">
            <el-form-item label="赋予角色" prop="roles">
              <el-checkbox-group v-model="changeForm.roles">
                <el-checkbox label="系统管理员">系统管理员</el-checkbox><br>
                <el-checkbox label="中心前台助理">中心前台助理</el-checkbox><br>
                <el-checkbox label="中心专职教师">中心专职教师</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
          <!-- 管辖范围 -->
          <div class="form-item">
            <el-form-item label="管辖范围" prop="jurisdictions">
              <el-select
                  v-model="changeForm.jurisdictions"
                  multiple
                  placeholder="请选择管辖范围"
                  collapse-tags
              >
                <el-option
                    v-for="(count, jurisdiction) in jurisdictionCount"
                    :key="jurisdiction"
                    :label="`${jurisdiction}（${count}人）`"
                    :value="jurisdiction"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 底部按钮 -->
          <div class="dialog-footer">
            <el-button @click="changeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitChange">提交</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 添加成员弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        :title="addDialogTitle"
        width="500px"
        @close="handleAddDialogClose"
        :before-close="handleAddDialogClose"
    >
      <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addRules"
          label-width="100px"
      >
        <div class="add-member-dialog">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="学号/账号" prop="account">
            <el-input v-model="addForm.account" placeholder="请输入学号/账号"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" placeholder="请输入密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="addForm.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="赋予角色" prop="roles">
            <el-checkbox-group v-model="addForm.roles">
              <el-checkbox label="系统管理员">系统管理员</el-checkbox>
              <el-checkbox label="助理">助理</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="负责校区" prop="jurisdiction">
            <el-select
                v-model="addForm.jurisdiction"
                multiple
                placeholder="请选择负责校区"
                collapse-tags
                style="width: 100%"
            >
              <el-option label="全校" value="全校"></el-option>
              <el-option label="A校区" value="A校区"></el-option>
              <el-option label="B校区" value="B校区"></el-option>
              <el-option label="马区" value="马区"></el-option>
              <el-option label="余区" value="余区"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="add-dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入成员弹窗 -->
    <el-dialog
        v-model="batchImportDialogVisible"
        :title="batchImportDialogTitle"
        width="500px"
    >
      <div class="batch-import-dialog">
        <p>导入教职工名单：</p>
        <el-button type="primary" @click="downloadTemplate">下载导入模板</el-button>
        <p class="tip">*能通过统一身份认证进入学校系统都可以导入</p>
        <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleUpload"
            :file-list="fileList"
            accept=".xls,.xlsx"
        >
          <el-button type="primary">上传名单</el-button>
        </el-upload>
      </div>
      <template #footer>
        <span class="batch-import-footer">
          <el-button @click="batchImportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchImport">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElDialog, ElForm, ElUpload } from "element-plus";
import { assistantMockData } from "../../api/mockData/asset.ts";

// 筛选条件
const statusFilter = ref("");
const roleFilter = ref("");
const searchKey = ref("");

// 分页数据
const currentPage = ref(1);
const pageSize = ref(5);
const totalCount = ref(0);

// 选中的行数据
const selectedRows = ref<any[]>([]);

// 弹窗相关
const changeDialogVisible = ref(false);
const changeDialogTitle = ref("批量变更");
const batchRows = ref<any[]>([]);
const addDialogVisible = ref(false);
const addDialogTitle = ref("添加成员");
// 批量导入弹窗
const batchImportDialogVisible = ref(false);
const batchImportDialogTitle = ref("批量导入成员");

// 上传相关
const fileList = ref<any[]>([]);
const selectedFile = ref<File | null>(null);

// 表单数据
const changeForm = ref({
  roles: [] as string[],
  jurisdictions: [] as string[]
});
const addForm = ref({
  name: "",
  account: "",
  password: "",
  phone: "",
  roles: [] as string[],
  jurisdiction: [] as string[]
});

// 表单验证规则
const changeRules = ref({
  roles: [{ required: true, message: '请选择赋予角色', trigger: 'change' }],
  jurisdictions: [{ required: true, message: '请选择管辖范围', trigger: 'change' }]
});
const addRules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  account: [{ required: true, message: '请输入学号/账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  roles: [{ required: true, message: '请选择赋予角色', trigger: 'change' }],
  jurisdiction: [{ required: true, message: '请选择负责校区', trigger: 'change' }]
});

const changeFormRef = ref<InstanceType<typeof ElForm> | null>(null);
const addFormRef = ref<InstanceType<typeof ElForm> | null>(null);

// 原始数据
const originalData = ref(assistantMockData);

// 统计每个管辖范围的人数
const jurisdictionCount = ref<Record<string, number>>({});
const calculateJurisdictionCount = () => {
  const count: Record<string, number> = {};
  originalData.value.forEach(item => {
    if (count[item.jurisdiction]) {
      count[item.jurisdiction]++;
    } else {
      count[item.jurisdiction] = 1;
    }
  });
  jurisdictionCount.value = count;
};

// 过滤后的数据
const filteredData = computed(() => {
  let result = originalData.value;
  if (statusFilter.value) result = result.filter(item => item.status === statusFilter.value);
  if (roleFilter.value) result = result.filter(item => item.role.includes(roleFilter.value));
  if (searchKey.value) result = result.filter(item =>
      item.name.includes(searchKey.value) || item.account.includes(searchKey.value)
  );
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return result.slice(startIndex, startIndex + pageSize.value);
});

// 获取列表数据
const getList = () => {
  setTimeout(() => {
    let tempData = originalData.value;
    if (statusFilter.value) tempData = tempData.filter(item => item.status === statusFilter.value);
    if (roleFilter.value) tempData = tempData.filter(item => item.role.includes(roleFilter.value));
    if (searchKey.value) tempData = tempData.filter(item =>
        item.name.includes(searchKey.value) || item.account.includes(searchKey.value)
    );
    totalCount.value = tempData.length;
  }, 300);
};

// 重置筛选条件
const resetFilters = () => {
  statusFilter.value = "";
  roleFilter.value = "";
  searchKey.value = "";
  currentPage.value = 1;
  selectedRows.value = [];
  getList();
};

// 处理选中行变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 显示变更对话框
const showChangeDialog = (row: any) => {
  batchRows.value = [row];
  changeForm.value = { roles: [], jurisdictions: [] };
  changeDialogTitle.value = `变更成员: ${row.name}`;
  changeDialogVisible.value = true;
};

// 批量变更
const batchChange = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要变更的记录");
    return;
  }
  batchRows.value = selectedRows.value;
  changeForm.value = { roles: [], jurisdictions: [] };
  changeDialogTitle.value = `批量变更 ${selectedRows.value.length} 个成员`;
  changeDialogVisible.value = true;
};

// 移除成员
const removeMember = (index: number) => {
  batchRows.value.splice(index, 1);
  if (batchRows.value.length === 0) {
    changeDialogVisible.value = false;
    ElMessage.warning("请至少保留一个成员");
  }
};

// 提交变更
const submitChange = () => {
  if (!changeFormRef.value) return;
  changeFormRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
          "确认提交变更？",
          "提示",
          { confirmButtonText: "确认", cancelButtonText: "取消", type: "warning" }
      ).then(() => {
        ElMessage.success("变更提交成功");
        changeDialogVisible.value = false;
        changeForm.value = { roles: [], jurisdictions: [] };
        getList(); // 刷新列表
      }).catch(() => ElMessage.info("已取消提交"));
    }
  });
};

// 分页变化处理
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  getList();
};

// 显示添加成员对话框
const showAddDialog = () => {
  addForm.value = { name: "", account: "", password: "", phone: "", roles: [], jurisdiction: [] };
  addDialogVisible.value = true;
};

// 处理添加对话框关闭
const handleAddDialogClose = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();  // 重置表单
  }
  addDialogVisible.value = false;  // 关闭弹窗
};

// 提交添加成员
const submitAdd = () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate((valid) => {
    if (valid) {
      const roleCode = addForm.value.roles.length === 1 ? "role1" : "role1;role2";
      const role = addForm.value.roles.join(":");
      const addTime = new Date().toLocaleString().replace(/\//g, "-");

      const newAssistant = {
        id: originalData.value.length > 0 ? originalData.value[originalData.value.length - 1].id + 1 : 1,
        name: addForm.value.name,
        account: addForm.value.account,
        jurisdiction: addForm.value.jurisdiction.join(","),
        phone: addForm.value.phone,
        role,
        roleCode,
        status: "激活",
        addTime
      };

      originalData.value.push(newAssistant);
      calculateJurisdictionCount();
      addDialogVisible.value = false;
      addForm.value = { name: "", account: "", password: "", phone: "", roles: [], jurisdiction: [] };
      ElMessage.success("添加成员成功");
      getList();

      nextTick(() => {
        const table = document.querySelector('.el-table__body-wrapper');
        if (table) table.scrollTop = table.scrollHeight;
      });
    }
  });
};

// 显示批量导入对话框
const showBatchImportDialog = () => {
  fileList.value = [];
  selectedFile.value = null;
  batchImportDialogVisible.value = true;
};

// 下载模板
const downloadTemplate = () => {
  // 定义CSV内容（Excel兼容格式）
  const csvContent = [
    '姓名,学号/账号,密码,手机号码,角色,负责校区',
    '张三,2025001,123456,13800138001,助理,A校区',
    '李四,2025002,123456,13900139002,助理,B校区',
    '王五,2025003,123456,13700137003,系统管理员,全校'
  ].join('\n');

  // 创建Blob对象
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.setAttribute('href', url);
  link.setAttribute('download', '助理导入模板.csv');
  link.style.visibility = 'hidden';

  // 添加到DOM并触发点击
  document.body.appendChild(link);
  link.click();

  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);

  ElMessage.success('模板下载成功');
};

// 处理文件上传
const handleUpload = (file: any) => {
  if (file.raw.type !== 'application/vnd.ms-excel' &&
      file.raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    ElMessage.error('请上传Excel文件(xls/xlsx)');
    return false;
  }

  fileList.value = [file];
  selectedFile.value = file.raw;
  return true;
};

// 提交批量导入
const submitBatchImport = () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }

  // 模拟上传处理
  ElMessageBox.confirm(
      '确认导入所选文件？',
      '提示',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    // 实际项目中应替换为真实的上传API调用
    setTimeout(() => {
      // 模拟导入成功，添加一些示例数据
      const mockImportData = [
        { id: originalData.value.length + 1, name: '导入用户1', account: 'import001', jurisdiction: 'A校区', phone: '13800000001', role: '助理', roleCode: 'role1', status: '激活', addTime: new Date().toLocaleString() },
        { id: originalData.value.length + 2, name: '导入用户2', account: 'import002', jurisdiction: 'B校区', phone: '13800000002', role: '助理', roleCode: 'role1', status: '激活', addTime: new Date().toLocaleString() }
      ];

      originalData.value = [...originalData.value, ...mockImportData];
      calculateJurisdictionCount();

      batchImportDialogVisible.value = false;
      fileList.value = [];
      selectedFile.value = null;
      ElMessage.success('批量导入成功，已添加2名成员');
      getList(); // 刷新列表
    }, 1000);
  }).catch(() => {
    ElMessage.info('已取消导入');
  });
};

onMounted(() => {
  calculateJurisdictionCount();
  getList();
});
</script>

<style scoped lang="scss">
.page-container {
  box-sizing: border-box;
  width: 100%;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    h2 { margin: 0; font-size: 18px; }
    .action-buttons { display: flex; gap: 8px; }
  }

  .search-form {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    margin-left: 10px;
    .search-select { width: 160px; }
    .search-input { width: 300px; }
  }

  .bottom-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
    margin-top: 20px;
  }

  /* 变更弹窗样式 */
  .batch-change-dialog {
    padding: 10px;

    .member-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 5px 10px;
      border-bottom: 1px solid #eee;
    }

    .form-item { margin: 10px 0; }

    .dialog-footer {
      text-align: right;
      margin-top: 20px;
    }
  }

  /* 添加成员弹窗样式 */
  .add-member-dialog {
    padding: 10px;

    .form-item { margin: 10px 0; }

    .add-dialog-footer {
      text-align: right;
      margin-top: 20px;
    }
  }

  /* 批量导入弹窗样式 */
  .batch-import-dialog {
    padding: 20px;

    p {
      margin-bottom: 15px;
    }

    .tip {
      color: #999;
      font-size: 12px;
      margin-top: 5px;
    }

    .upload-demo {
      margin-top: 15px;
    }
  }

  .batch-import-footer {
    text-align: right;
    margin-top: 20px;
  }
}
</style>